﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using Store.WP7.Framework.Services;

namespace Store.WP7.Data
{
    public class PushNotificationsService : ServiceBase
    {
        public void SuscribeToPushNotificationAsync(int customerId, string url, Action<ServiceResult> callback)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(state =>
            {
                ServiceResult serviceResult = new ServiceResult();
                try
                {
                    _storeServiceClient.BeginSubscribeToPush(customerId, url, new AsyncCallback(asyncResult =>
                    {
                        try
                        {
                            _storeServiceClient.EndSubscribeToPush(asyncResult);
                            if(callback != null)
                                callback(serviceResult);
                        }
                        catch (Exception xcp)
                        {
                            serviceResult.Error = xcp;
                            if (callback != null)
                                callback(serviceResult);
                        }
                    }), state);
                }
                catch (Exception e)
                {
                    serviceResult.Error = e;
                    callback(serviceResult);
                }
            }));
        }

        public void UnsubscribeFromPushNotification(string url, Action<ServiceResult> callback)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(state =>
            {
                ServiceResult serviceResult = new ServiceResult();
                try
                {
                    _storeServiceClient.BeginUnsubscribeFromPush(url, new AsyncCallback(asyncResult =>
                    {
                        try
                        {
                            _storeServiceClient.EndUnsubscribeFromPush(asyncResult);
                            callback(serviceResult);
                        }
                        catch (Exception xcp)
                        {
                            serviceResult.Error = xcp;
                            callback(serviceResult);
                        }
                    }), state);
                }
                catch (Exception e)
                {
                    serviceResult.Error = e;
                    callback(serviceResult);
                }
            }));
        }
    }
}
